package com.saris.primego.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.saris.primego.common.constant.MessageConstant;
import com.saris.primego.common.context.BaseContext;
import com.saris.primego.common.exception.AddressBookBusinessException;
import com.saris.primego.common.exception.EntityNotFoundException;
import com.saris.primego.common.exception.OrderBusinessException;
import com.saris.primego.common.exception.ShoppingCartBusinessException;
import com.saris.primego.common.result.PageResult;
import com.saris.primego.common.utils.HttpClientUtil;
import com.saris.primego.common.utils.WeChatPayUtil;
import com.saris.primego.dao.*;
import com.saris.primego.pojo.dto.*;
import com.saris.primego.pojo.entity.*;
import com.saris.primego.pojo.vo.*;
import com.saris.primego.service.OrderService;
import com.saris.primego.websocket.WebSocketServer;
import jakarta.persistence.criteria.Predicate;
import jakarta.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    private final AddressBookRepository addressBookRepository;
    private final ShoppingCartRepository shoppingCartRepository;
    private final OrderRepository orderRepository;
    private final ModelMapper modelMapper;
    private final OrderDetailRepository orderDetailRepository;
    private final UserRepository userRepository;
    private final WeChatPayUtil weChatPayUtil;
    private final WebSocketServer webSocketServer;

    public OrderServiceImpl(AddressBookRepository addressBookRepository, ShoppingCartRepository shoppingCartRepository, OrderRepository orderRepository, ModelMapper modelMapper, OrderDetailRepository orderDetailRepository, UserRepository userRepository, WeChatPayUtil weChatPayUtil, WebSocketServer webSocketServer) {
        this.addressBookRepository = addressBookRepository;
        this.shoppingCartRepository = shoppingCartRepository;
        this.orderRepository = orderRepository;
        this.modelMapper = modelMapper;
        this.orderDetailRepository = orderDetailRepository;
        this.userRepository = userRepository;
        this.weChatPayUtil = weChatPayUtil;
        this.webSocketServer = webSocketServer;
    }

    /**
     * 用户下单
     */
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {

        //1. 处理各种业务异常（地址簿为空、购物车数据为空）
        AddressBook addressBook = addressBookRepository.findById(ordersSubmitDTO.getAddressBookId()).orElseThrow(() -> new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL));

        if (addressBook == null) {
            //抛出业务异常
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //检查用户的收货地址是否超出配送范围
        //checkOutOfRange(addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());

        //查询当前用户的购物车数据
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCarts = shoppingCartRepository.findAllByUserId(userId).orElseThrow(() -> new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL));

        if (shoppingCarts == null || shoppingCarts.isEmpty()) {
            //抛出业务异常
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //2. 向订单表插入1条数据
        Orders order = modelMapper.map(ordersSubmitDTO, Orders.class);
        order.setOrderTime(LocalDateTime.now());
        order.setPayStatus(Orders.UN_PAID);
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setPhone(addressBook.getPhone());
        order.setConsignee(addressBook.getConsignee());
        order.setUserId(userId);

        Orders saved = orderRepository.saveAndFlush(order);

        //3. 向订单明细表插入n条数据
        List<OrderDetail> orderDetails = new ArrayList<>();
        shoppingCarts.forEach(shoppingCart -> {
            OrderDetail orderDetail = modelMapper.map(shoppingCart, OrderDetail.class);
            orderDetail.setId(null);
            orderDetail.setOrderId(saved.getId());//设置当前订单明细关联的订单Id

            orderDetails.add(orderDetail);
        });

        orderDetailRepository.saveAllAndFlush(orderDetails);

        //4. 清空当前用户的购物车数据
        shoppingCartRepository.deleteByUserId(userId);

        //5. 封装VO返回结果
        return OrderSubmitVO.builder()
                .id(saved.getId())
                .orderTime(saved.getOrderTime())
                .orderNumber(saved.getNumber())
                .orderAmount(saved.getAmount())
                .build();
    }

    /**
     * 订单支付
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userRepository.findById(userId).orElseThrow(()->new EntityNotFoundException("用户不存在"));

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal("0.01"), //支付金额，单位 元
                "鲜行者订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        return vo;
    }

    /**
     * 支付成功，修改订单状态
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        List<Orders> ordersList = orderRepository.getByNumberAndUserId(outTradeNo, userId);
        if (ordersList == null || ordersList.isEmpty()) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        Orders ordersDB = ordersList.getFirst();

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderRepository.saveAndFlush(orders);

        //通过websocket向客户端浏览器推送消息 type orderId content
        Map<String, Object> map = new HashMap<>();
        map.put("type", 1); // 1表示来单提醒 2表示客户催单
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号：" + outTradeNo);

        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);

    }


    /**
     * 检查客户的收货地址是否超出配送范围
     */
    private void checkOutOfRange(String address) {
        Map<String, String> map = new HashMap<>();
//        map.put("address",shopAddress);
        map.put("output", "json");
//        map.put("ak",ak);

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address", address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin", shopLngLat);
        map.put("destination", userLngLat);
        map.put("steps_info", "0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.getFirst()).get("distance");

        if (distance > 5000) {
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }


    /**
     * 用户端订单分页查询
     */
    public PageResult<OrderVO> pageQuery4User(int pageNum, int pageSize, Integer status) {
        // 设置分页
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize);

        // 动态构建查询条件
        Specification<Orders> spec = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();

            // 当 status 不为空时，添加 status 条件
            if (status != null) {
                predicates.add(cb.equal(root.get("status"), status));
            }

            if (predicates.isEmpty()) {
                return cb.conjunction();

            } else {
                return cb.and(predicates.toArray(new Predicate[0]));
            }
        };

        Page<Orders> all = orderRepository.findAll(spec, pageable);
        long totalElements = all.getTotalElements();
        List<Orders> content = all.getContent();

        List<OrderVO> orderVOList = new ArrayList<>();
        for (Orders orders : content) {
            List<OrderDetail> orderDetailList = orderDetailRepository.getAllByOrderId(orders.getId());

            OrderVO orderVO = modelMapper.map(orders, OrderVO.class);
            orderVO.setOrderDetailList(orderDetailList);

            orderVOList.add(orderVO);
        }


        return new PageResult<>(totalElements, orderVOList);
    }

    /**
     * 查询订单详情
     */
    public OrderVO details(Long id) {
        // 根据id查询订单
        Orders orders = orderRepository.findById(id).orElseThrow(()->new EntityNotFoundException(MessageConstant.ORDER_NOT_FOUND));

        // 查询该订单对应的菜品/套餐明细
        List<OrderDetail> orderDetailList = orderDetailRepository.findAllByOrderId(id);

        // 将该订单及其详情封装到OrderVO并返回
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);

        return orderVO;
    }

    /**
     * 用户取消订单
     */
    public void userCancelById(Long id) throws Exception {
        // 根据id查询订单
        Orders ordersDB = orderRepository.findById(id).orElseThrow(()->new EntityNotFoundException(MessageConstant.ORDER_NOT_FOUND));

        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (ordersDB.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());

        // 订单处于待接单状态下取消，需要进行退款
        if (ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //调用微信支付退款接口
            weChatPayUtil.refund(
                    ordersDB.getNumber(), //商户订单号
                    ordersDB.getNumber(), //商户退款单号
                    new BigDecimal("0.01"),//退款金额，单位 元
                    new BigDecimal("0.01"));//原订单金额

            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }

        // 更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderRepository.saveAndFlush(orders);
    }

    /**
     * 再来一单
     */
    public void repetition(Long id) {
        // 查询当前用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单id查询当前订单详情
        List<OrderDetail> orderDetailList = orderDetailRepository.getAllByOrderId(id);

        // 将订单详情对象转换为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();

            // 将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtils.copyProperties(x, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());

        // 将购物车对象批量添加到数据库
        shoppingCartRepository.saveAllAndFlush(shoppingCartList);
    }

    /**
     * 订单搜索
     */
    public PageResult<OrderVO> conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        String number = ordersPageQueryDTO.getNumber();
        String phone = ordersPageQueryDTO.getPhone();
        LocalDateTime beginTime = ordersPageQueryDTO.getBeginTime();
        LocalDateTime endTime = ordersPageQueryDTO.getEndTime();
        Integer status = ordersPageQueryDTO.getStatus();
        int page = ordersPageQueryDTO.getPage();
        int pageSize = ordersPageQueryDTO.getPageSize();

        //搜索条件：订单号、手机号、下单时间区间
        Pageable pageable = PageRequest.of(page - 1, pageSize);

        // 动态构建查询条件
        Specification<Orders> spec = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();

            // 当 name 不为空时，添加 name 条件
            if (number != null && !number.trim().isEmpty()) {
                predicates.add(cb.like(root.get("number"), "%" + number + "%"));
            }
            // 当 categoryId 不为空时，添加 categoryId 条件
            if (phone != null) {
                predicates.add(cb.like(root.get("phone"), phone));
            }
            // 当 beginTime 不为空时，添加 beginTime 条件
            if (beginTime != null) {
                predicates.add(cb.greaterThanOrEqualTo(root.get("beginTime"), beginTime));
            }
            // 当 endTime 不为空时，添加 endTime 条件
            if (endTime != null) {
                predicates.add(cb.lessThanOrEqualTo(root.get("endTime"), endTime));
            }
            // 当 status 不为空时，添加 status 条件
            if (status != null) {
                predicates.add(cb.equal(root.get("status"), status));
            }
            if (predicates.isEmpty()) {
                return cb.conjunction();

            } else {
                return cb.and(predicates.toArray(new Predicate[0]));
            }
        };

        Page<Orders> orders = orderRepository.findAll(spec, pageable);

        long totalElements = orders.getTotalElements();
        List<Orders> content = orders.getContent();

        List<OrderVO> orderVOList = new ArrayList<>();
        for (Orders o : content) {
            AddressBook addressBook = addressBookRepository.findById(o.getAddressBookId()).orElseThrow(()->new EntityNotFoundException(MessageConstant.ADDRESSBOOK_NOT_FOUND));
            o.setAddress(addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());

            List<OrderDetail> orderDetailList = orderDetailRepository.getAllByOrderId(o.getId());

            OrderVO orderVO = modelMapper.map(o, OrderVO.class);

            String orderDishesStr = getOrderDishesStr(o);
            orderVO.setOrderDishes(orderDishesStr);
            orderVO.setOrderDetailList(orderDetailList);

            orderVOList.add(orderVO);
        }


        return new PageResult<>(totalElements, orderVOList);
    }

    /**
     * 根据订单id获取菜品信息字符串
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailRepository.findAllByOrderId(orders.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            return x.getName() + "*" + x.getNumber() + ";";
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }

    /**
     * 各个状态的订单数量统计
     */
    public OrderStatisticsVO statistics() {
        // 根据状态，分别查询出待接单、待派送、派送中的订单数量
        int toBeConfirmed = orderRepository.findAllByStatus(Orders.TO_BE_CONFIRMED).size();
        int confirmed = orderRepository.findAllByStatus(Orders.CONFIRMED).size();
        int deliveryInProgress = orderRepository.findAllByStatus(Orders.DELIVERY_IN_PROGRESS).size();

        // 将查询出的数据封装到orderStatisticsVO中响应
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    /**
     * 接单
     */
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = orderRepository.findById(ordersConfirmDTO.getId()).orElseThrow(()->new EntityNotFoundException(MessageConstant.ORDER_NOT_FOUND));
        orders.setStatus(Orders.CONFIRMED);

        orderRepository.saveAndFlush(orders);
    }

    /**
     * 拒单
     */
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        // 根据id查询订单
        Orders ordersDB = orderRepository.findById(ordersRejectionDTO.getId()).orElseThrow(()->new EntityNotFoundException(MessageConstant.ORDER_NOT_FOUND));

        // 订单只有存在且状态为2（待接单）才可以拒单
        if (!ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (Objects.equals(payStatus, Orders.PAID)) {
            //用户已支付，需要退款
            String refund = weChatPayUtil.refund(
                    ordersDB.getNumber(),
                    ordersDB.getNumber(),
                    new BigDecimal("0.01"),
                    new BigDecimal("0.01"));
            log.info("申请退款：{}", refund);
        }

        // 拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
        ordersDB.setId(ordersDB.getId());
        ordersDB.setStatus(Orders.CANCELLED);
        ordersDB.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        ordersDB.setCancelTime(LocalDateTime.now());

        orderRepository.saveAndFlush(ordersDB);
    }

    /**
     * 取消订单
     */
    public void cancel(OrdersCancelDTO ordersCancelDTO) throws Exception {
        // 根据id查询订单
        Orders ordersDB = orderRepository.findById(ordersCancelDTO.getId()).orElseThrow(()->new EntityNotFoundException(MessageConstant.ORDER_NOT_FOUND));


        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus == 1) {
            //用户已支付，需要退款
            String refund = weChatPayUtil.refund(
                    ordersDB.getNumber(),
                    ordersDB.getNumber(),
                    new BigDecimal("0.01"),
                    new BigDecimal("0.01"));
            log.info("申请退款：{}", refund);
        }

        // 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersCancelDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());

        orderRepository.saveAndFlush(orders);
    }

    /**
     * 派送订单
     */
    public void delivery(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderRepository.findById(id).orElseThrow(()->new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND));


        // 校验订单是否存在，并且状态为3
        if (!ordersDB.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 更新订单状态,状态转为派送中
        ordersDB.setStatus(Orders.DELIVERY_IN_PROGRESS);

        orderRepository.saveAndFlush(ordersDB);
    }

    /**
     * 完成订单
     */
    public void complete(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderRepository.findById(id).orElseThrow();

        // 校验订单是否存在，并且状态为4
        if (!ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 更新订单状态,状态转为完成
        ordersDB.setStatus(Orders.COMPLETED);
        ordersDB.setDeliveryTime(LocalDateTime.now());

        orderRepository.saveAndFlush(ordersDB);
    }

    /**
     * 客户催单
     */
    public void reminder(Long id) {
        // 根据id查询订单
        Orders orders = orderRepository.findById(id).orElseThrow(() -> new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND));

        // 校验订单是否存在
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 声明时指定泛型类型
        Map<String, Object> map = new HashMap<>();
        map.put("type", 2);          // Integer
        map.put("orderId", id);      // Long（假设 id 是 Long 类型）
        map.put("content", "订单号：" + orders.getNumber()); // String

        //通过websocket向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }
}
